
/**
 * @author Jose Luis Cruz
 *          Daniel Uribe
 *          Josel Valadez
 *
 * Midlet for consulting scholar appointments.
 */

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.pim.EventList.*;
import java.io.*;
import java.lang.*;

public class Asesorias extends MIDlet implements CommandListener, Runnable{
     private static String mURL =
    "http://josel.quetzal-hosting.com/asesorias/movil.php";
  private Form mForm;
  private Command mExitCommand;
  private Command mSubmitCommand;
  private TextField inputUsuario;
  private TextField inputPassword;
  private StringItem respuesta = new StringItem(null,null);
  private StringItem eventosR = new StringItem(null, null);
  private String usuario;
  private String password;
  private DataInputStream in = null;

  public void startApp() {
    if (mForm == null) {
      String url = getAppProperty("text-url");
      if (url != null && !url.equals("")) mURL = url;
      mForm = new Form("Asesorias Erika Vilches");
      Gauge gauge = new Gauge("Loading...", false,
          Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING);
      mForm.append(gauge);
      mExitCommand = new Command("Exit", Command.EXIT, 0);
      mSubmitCommand = new Command("Submit", Command.OK, 1);
      mForm.deleteAll();
      mForm.addCommand(mExitCommand);
      mForm.addCommand(mSubmitCommand);
      mForm.setCommandListener(this);
      Thread t = new Thread(this);
      t.start();
    }

    Display.getDisplay(this).setCurrent(mForm);
  }

  public void pauseApp() {}

  public void destroyApp(boolean unconditional) {}

  public void commandAction(Command c, Displayable s) {
    if (c.getCommandType() == Command.EXIT) {
      destroyApp(true);
      notifyDestroyed();
    }
    if (c.getCommandType() == Command.OK){
        usuario = inputUsuario.getString();
        password = inputPassword.getString();
        sendPost();
    }
  }

  public String sendPost(){
        mForm.removeCommand(mSubmitCommand);
        DataOutputStream os = null;
        DataInputStream is = null;
        String message = "";
        HttpConnection hc = null;
        StringBuffer stringBuffer = new StringBuffer();

        try{
        hc = (HttpConnection)Connector.open(mURL);
        hc.setRequestMethod(HttpConnection.POST);
        hc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        os = hc.openDataOutputStream();
        String mensaje = "Usuario="+codifica(usuario)+"&Password="+codifica(password);
        hc.setRequestProperty("Content-Length", Integer.toString(mensaje.length()));
        os.write(mensaje.getBytes());

        int code = hc.getResponseCode();

        if(code == 200){
           in = hc.openDataInputStream();
           int ch;
           while ((ch = in.read()) != -1){
                stringBuffer.append((char)ch);
           }
           eventosR.setText(stringBuffer.toString());

           mForm.addCommand(mSubmitCommand);
        }else{
            respuesta.setText("No se pudo "+Integer.toString(code));
            }

        }catch(IOException ioe){
            message = "ERROR";
            }
        finally{
            try{
                if(hc != null)
                    hc.close();
            }
            catch(IOException ignored){}
            try{
                if(is != null){
                    is.close();
                }
            }
            catch(IOException ignored){}
            try{
                if(os != null){
                    os.close();
                }
            }
            catch(IOException ignored){}
        }

        return message;
  }

  public void run() {
    try {
        inputUsuario = new TextField("Usuario", "", 16, TextField.NUMERIC);
        mForm.append(inputUsuario);

        inputPassword = new TextField("Password", "", 16, TextField.PASSWORD);
        mForm.append(inputPassword);

        mForm.append(respuesta);
        mForm.append(eventosR);

    }
    catch (IllegalArgumentException iae) {
        mForm.append("Bad text file.");
    }
    catch (SecurityException se) {
        mForm.append("Don't have permission.");
    }
    finally { clearGauge(); }
  }


  private void clearGauge() {
    for (int i = 0; i < mForm.size(); i++) {
      Item item = mForm.get(i);
      if (item instanceof Gauge)
        mForm.delete(i--);
    }
  }

  	private String codifica(String msg) {
		StringBuffer r = new StringBuffer();
		char[] a = msg.toCharArray();
		for (int i = 0; i < a.length; i++) {
			r.append("%" + Integer.toString(a[i], 16));
		}
		return r.toString();
	}
}
